﻿/**
 * DotNetFetion, a simple fetion library written by C#
 * Copyright (C) 2009  zucky
 * 
 * This file is part of DotNetFetion.
 * 
 * DotNetFetion is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * DotNetFetion is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with DotNetFetion.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 本人实现的该类库是基本上参看php版本的fetion，具体是谁写的我在其源代码中没有注明，
 * 所以我也不知道是谁，在此表示感谢。飞信是中国移动的产品，归中国移动公司所有，
 * 请不要将该类库用于非法途径和商业途径，与此产生的一切法律后果与本人无关。
 * 
 * 有任何问题，可以访问我的博客：http://zucky.cnblogs.com 留言，或发email至ssdut@126.com，
 * 使用本类库请遵循GPL v3协议。
 **/

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Text.RegularExpressions;

namespace com.dlut.ssdut.zucky.DotNetFetion
{
    internal class SIPC
    {
        string ip;
        int port;
        Socket socket;

        public SIPC(string SIPC_addr)
        {
            string[] addr = SIPC_addr.Split(':');
            this.ip = addr[0];
            this.port = int.Parse(addr[1]);

            this.SocketInit();

        }

        ~SIPC()
        {
            SocketClose();
        }

        // 发送 SIP-C 请求
        public string Request(string sip_request)
        {

            this.SocketWrite(Encoding.UTF8.GetBytes(sip_request));
            string response = this.SocketRead();

            return response;
        }

        // 初始化 socket 为 SIP-C 请求准备环境
        private void SocketInit()
        {
            // 连接指定的 IP 和 端口
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(this.ip, this.port);
        }

        private void SocketClose()
        {
            this.socket.Close();
        }
        // 往套接字写数据
        private void SocketWrite(byte[] data)
        {
            this.socket.Send(data);
        }

        // 从套接字读数据
        private string SocketRead()
        {
            string socketContent = "";
            byte[] buffer = new byte[4];
            do
            {
                int len = socket.Receive(buffer, 4, SocketFlags.None);
                socketContent += Encoding.UTF8.GetString(buffer, 0, len);
            }
            while (!socketContent.Contains("\r\n\r\n"));
            Regex regex = new Regex("L: (?<length>([0-9]+))");
            Match match = regex.Match(socketContent);
            if (match.Success)
            {
                int length = int.Parse(match.Result("${length}"));
                byte[] bf = new byte[length];
                this.socket.Receive(bf, length, SocketFlags.None);
                socketContent += Encoding.UTF8.GetString(bf);
            }

            return socketContent;

        }
    }
}
